<?php
/**
 * 微信公众平台 PHP SDK 示例文件
 *
 * @author NetPuter <netputer@gmail.com>
 */

define('ROOT_PATH', dirname(__FILE__));


include(ROOT_PATH . '/eccore/ecmall.php');

ecm_define(ROOT_PATH . '/data/config.inc.php');
ecm_define(ROOT_PATH . '/data/settings.inc.php');

include(ROOT_PATH . '/includes/global.lib.php');
include(ROOT_PATH . '/includes/libraries/time.lib.php');
include(ROOT_PATH . '/eccore/controller/app.base.php');
include(ROOT_PATH . '/includes/ecapp.base.php');
require(ROOT_PATH . '/app/frontend.base.php');   //模型基础类
require(ROOT_PATH . '/m/Wechat.php');   //模型基础类
/* 定义配置信息 */

/* 环境 */
define('CHARSET', substr(LANG, 3));

/**
 * 微信公众平台演示类
 */
class MyWechat extends Wechat {
	function gmtime()
	{
		return (time() - date('Z'));
	}

	function getAccessToken($refresh=false){
		$access_token = null;
		$filename=ROOT_PATH . '/data/settings.inc.php';
		/* 载入配置项 */
		$settingconfig = include($filename);
		if(!$refresh&&$settingconfig["access_token"]){
			if($settingconfig["access_expires_in"]>=time()){
				$access_token = $settingconfig["access_token"];
			}
		}
		if(empty($access_token)){
			$WX_APPID='wx6d434637b263c347';
			$WX_SECRET='6909b33a488b1d2bf5efaf58641613e4';
			$re = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$WX_APPID&secret=$WX_SECRET");
			$re = json_decode($re);
			if(property_exists($re,"errcode")){
				throw new Exception($re->errcode);
			}
			if($re->access_token){
				$access_token = $re->access_token;
				$settingconfig["access_token"]=$re->access_token;
				$settingconfig["access_expires_in"]=time()+$re->expires_in-60;
				file_put_contents($filename, "<?php \nreturn " . var_export($settingconfig , true) . ";\n?>");
			}
		}
		return $access_token;
	}
	/**
	 * 用户关注时触发，回复「欢迎关注」
	 *
	 * @return void
	 */
	public function onSubscribe() {
		try{
			$db =&db();
			$openid=$this->getRequest('fromusername');
			$subscribe = ($this->getRequest('EventKey'));
			$subuser = $this->getRequest('tousername');
			$subscribe=substr($subscribe,8);//qrscene_3

			$sql="select user_id, user_name, reg_time, last_login, last_ip from cw_member where weixin = '{$openid}'";
			$user_info=$db->getRow($sql);

			if (!$user_info)
			{
				$wx='';
				try{
					$access_token=$this->getAccessToken();
					if($access_token){
						$wx=file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN");
						$wx = json_decode($wx);
						if(property_exists($wx,"errcode")){
							$access_token=$this->getAccessToken(true);
							if($access_token){
								$wx=file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN");
								$wx = json_decode($wx);
							}
						}
					}
				}
				catch(Exception $e){
					$this->responseText($e->getMessage());
				}

				if($wx){

					$sql = "insert into cw_member set
					user_name='$openid',language='$wx->language',city='$wx->city',province='$wx->province',headimgurl='$wx->headimgurl',real_name='$wx->nickname'
					,status='关注',weixin='".$openid."',reg_time=".gmtime().",user_type='weixin'";
				}
				$file = fopen("test3.txt","w");
				fwrite($file,$sql);
				$db->query($sql);
			}
		}
		catch(Exception $e){
			$this->responseText($e->getMessage());
		}
		//echo '欢迎关注';
		$sql = "SELECT a.* FROM cw_article a
    LEFT JOIN cw_acategory AS ac ON ac.cat_id = a.cat_id  WHERE ac.cat_name='关注提示' limit 1";
			
		$article = $db->getRow($sql);
		$items[]=new NewsResponseItem($article['title'], $article['content'],
		SITE_URL.$article['file_url'],'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8dde4f3adafbab56&redirect_uri=http://wap.hflvxingzhe.com/weixin.php?upp='.SITE_URL.'m/'."article.php?act=info|id=".$article['article_id'].'&response_type=code&scope=snsapi_base&state=STATE&wechat_redirect');

		$this->responseNews($items);
	}


	/**
	 * 用户取消关注时触发
	 *
	 * @return void
	 */
	protected function onUnsubscribe() {
		$db =$this->db();
		$openid=$this->getRequest('fromusername');
		$sql="select * from gh_users where weixin='".$openid."'";
		$file = fopen("test1.txt","w");
		fwrite($file,$sql);
		$user=$db->getRow($sql);
		if($user){
			$sql = "update gh_users set status='取消关注',leavedate=".$this->gmtime()." where weixin='".$openid."'";
			$query=$db->query($sql);
		}
		// 「悄悄的我走了，正如我悄悄的来；我挥一挥衣袖，不带走一片云彩。」
	}

	protected function onScan(){
		try{
			$db =$this->db();
			$openid=$this->getRequest('fromusername');
			$subscribe = ($this->getRequest('EventKey'));
			$subuser = $this->getRequest('tousername');
			$subscribe=substr($subscribe,8);//qrscene_3
			$sql="select * from gh_users where weixin='".$openid."'";
			$user=$db->getRow($sql);
			if(!$user){
				$wx='';
				try{
					$access_token=$this->getAccessToken();
					if($access_token){
						$wx=file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN");
						$wx = json_decode($wx);
						if(property_exists($wx,"errcode")){
							$access_token=$this->getAccessToken(true);
							if($access_token){
								$wx=file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN");
								$wx = json_decode($wx);
							}
						}
					}
				}
				catch(Exception $e){
					$this->responseText($e->getMessage());
				}
				if($wx){
					$sql = "insert into gh_users set regsubscribe='$subscribe',regsubuser='$subuser',subscribe='$subscribe',subuser='$subuser',username='$wx->nickname',language='$wx->language',city='$wx->city',province='$wx->province',country='$wx->country',headimgurl='$wx->headimgurl',status='关注',weixin='".$openid."',reg_time=".$this->gmtime();
				}
				else{
					$sql = "insert into gh_users set regsubscribe='$subscribe',regsubuser='$subuser',subscribe='$subscribe',subuser='$subuser',status='关注',weixin='".$openid."',reg_time=".$this->gmtime();
				}
				$query=$db->query($sql);
			}
			else{
				$sql = "update gh_users set subscribe='$subscribe',subuser='$subuser',status='关注',reg_time=".$this->gmtime()." where weixin='".$openid."'";
				$query=$db->query($sql);
			}
		}
		catch(Exception $e){
			$this->responseText($e->getMessage());
		}
		//echo '欢迎关注';
		$this->responseText('欢迎关注。');
	}

	/**
	 * 用户扫描时触发，用于子类重写
	 *
	 * @return void
	 */
	protected function onClick() {
		try{
			$openid=$this->getRequest('fromusername');
			$subuser = $this->getRequest('tousername');
			$eventkey=$this->getRequest('EventKey');
			$db =$this->db();
			if($eventkey=='click_tel'){
				$this->responseText('客服电话:4006580088');
			}
		}
		catch(Exception $e){
			$this->responseText($e->getMessage());
		}
	}

	/**
	 * 收到文本消息时触发，回复收到的文本消息内容
	 *
	 * @return void
	 */
	protected function onText() {
		/*try{
			$openid=$this->getRequest('fromusername');
			$subuser = $this->getRequest('tousername');
			$content = intval($this->getRequest('content'));
			$db =$this->db();
			if($content){
			$content = $db->getRow("select * from ws_acategory where sort_order=0");
			if($content){
			$item[]=new NewsResponseItem($content['cate_name'], $content['description'], SITE_URL."/".$content['pic'], SITE_URL."/index.php?app=article&cid=".$content['cate_id']."&wxid=$openid");

			$ws_article = $db->getAll("select * from ws_article where cate_id=".$content['cate_id']." and recommend=1 order by sort_order,add_time desc limit 0,8");
			if($ws_article){
			if(count($ws_article)==1){
			$item=null;
			$val = $ws_article[0];
			$item[]=new NewsResponseItem($val['title'], str_replace('&nbsp;','',strip_tags($val['content'])), SITE_URL."/".$val['apic'], empty($val['link'])?(SITE_URL."/index.php?app=article&act=view&aid=".$val['article_id']."&wxid=$openid"):$val['link']);
			}
			else{
			foreach($ws_article as $key=>$val){
			if(empty($item))
			$item[]=new NewsResponseItem($val['title'], str_replace('&nbsp;','',strip_tags($val['content'])), SITE_URL."/".$val['apic'], (SITE_URL."/index.php?app=article&cid=".$val['cate_id']."&wxid=$openid"));
			else
			$item[]=new NewsResponseItem($val['title'], strip_tags($val['content']), SITE_URL."/".$val['apic'], empty($val['link'])?(SITE_URL."/index.php?app=article&act=view&aid=".$val['article_id']."&wxid=$openid"):$val['link']);
			}
			}
			}
			$this->responseNews($item);
			}

			$content = $db->getRow("select * from ws_acategory where sort_order=".$content);
			if($content){
			$item[]=new NewsResponseItem($content['cate_name'], $this->contentstrip($content['description']), SITE_URL."/".$content['pic'], SITE_URL."/index.php?app=article&cid=".$content['cate_id']."&wxid=$openid");
			$ws_article = $db->getAll("select * from ws_article where cate_id=".$content['cate_id']." and recommend=1 order by sort_order,add_time desc limit 0,5");
			if($ws_article){
			if(count($ws_article)==1){
			$item=null;
			$val = $ws_article[0];
			$item[]=new NewsResponseItem($val['title'], $this->contentstrip($val['content']), SITE_URL."/".$val['apic'], (SITE_URL."/index.php?app=article&act=view&aid=".$val['article_id']."&wxid=$openid"));
			}
			else{
			foreach($ws_article as $key=>$val){
			if(empty($item))
			$item[]=new NewsResponseItem($val['title'], $this->contentstrip($val['content']), SITE_URL."/".$val['apic'], (SITE_URL."/index.php?app=article&cid=".$val['cate_id']."&wxid=$openid"));
			else
			$item[]=new NewsResponseItem($val['title'], $this->contentstrip($val['content']), SITE_URL."/".$val['apic'], (SITE_URL."/index.php?app=article&act=view&aid=".$val['article_id']."&wxid=$openid"));
			}
			}
			}
			$this->responseNews($item);
			}
			}
			$item = "不存在".$this->getRequest('content')."的幸福攻略请输入序号，获取属于您的幸福攻略：";
			$ws_acategory = $db->getAll("select * from ws_acategory order by sort_order,dateline desc");
			if($ws_acategory){
			foreach($ws_acategory as $key=>$val){
			$item.='
			'.$val['sort_order'].'.'.$val['cate_name'];
			}
			$this->responseText($item);
			}
			}
			catch(Exception $e){
			$this->responseText($e->getMessage());
			}*/
	}
	function contentstrip($c){
		return substr(str_replace('&nbsp;','',strip_tags($c)),0,60);
	}
	/**
	 * 收到图片消息时触发，回复由收到的图片组成的图文消息
	 *
	 * @return void
	 */
	protected function onImage() {
		$items = array(
		new NewsResponseItem('标题一', '描述一', $this->getRequest('picurl'), $this->getRequest('picurl')),
		new NewsResponseItem('标题二', '描述二', $this->getRequest('picurl'), $this->getRequest('picurl')),
		);

		//$this->responseNews($items);
	}

	/**
	 * 收到地理位置消息时触发，回复收到的地理位置
	 *
	 * @return void
	 */
	protected function onLocation() {

		$openid=$this->getRequest('fromusername');
		$subuser = $this->getRequest('tousername');
		$Latitude=$this->getRequest('Latitude');
		$Longitude=$this->getRequest('Longitude');
		$Prec=$this->getRequest('Precision');
		$CreateTime=$this->getRequest('CreateTime');
		$db =$this->db();
		$db->query("update gh_users set Latitude='$Latitude',Longitude='$Longitude',Prec='$Prec',locationtime='$CreateTime' where weixin='$openid'");
	}

	/**
	 * 收到链接消息时触发，回复收到的链接地址
	 *
	 * @return void
	 */
	protected function onLink() {
		$this->responseText('收到了链接：' . $this->getRequest('url'));
	}

	/**
	 * 收到未知类型消息时触发，回复收到的消息类型
	 *
	 * @return void
	 */
	protected function onUnknown() {
		$this->responseText('收到了未知类型消息：' . $this->getRequest('msgtype'));
	}

}
$wechat = new MyWechat('weixin', TRUE);
$wechat->run();